import envConfig from '../utils/env'

const envName = wx.getAccountInfoSync().miniProgram.envVersion
const baseUrl = envConfig[envName] ? envConfig[envName].baseUrl : envConfig.prod.baseUrl
let requestList = new Set()

export default function request(url, method = 'GET', data = {}) {
  return new Promise((resolve, reject) => {
    try {
      // JSON化请求数据,数据循环引用可能导致JSON化失败
      var requstItem = url + method + JSON.parse(JSON.stringify(data))
      if (requestList.has(requstItem)) {
        reject(Error('请勿重复请求'))
      } else {
        requestList.add(requstItem)
      }
    } catch (error) {
      reject(error)
    }
    wx.request({
      url: baseUrl + url,
      method,
      header: {
        // 'content-type': method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json', // 默认值
        'content-type': 'application/json', // 默认值
        "Authorization": wx.getStorageSync('token') ? 'Bearer ' + wx.getStorageSync('token') : ''
      },
      ...data,
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      },
      complete: () => {
        requestList.delete(requstItem)
      }
    })
  })
}

request.__proto__.get = function (url, data = {}) {
  return request(url, 'GET', data)
}

request.__proto__.post = function (url, data = {}, config = {}) {
  return request(url, 'POST', {
    data,
    ...config
  })
}